import { ref, reactive, onMounted, } from "vue";
import { useRoute } from "vue-router";
import qs from "qs";
import { ElMessage } from "element-plus";
import {
  GetDictionaryByDictCode,
  GetHaveAssetTransferedProjectName,
  AssetSecuritizationCreate,
  GetExcessCollateral,
  GetCreditEnhancementInfoByAssetPoolId,
  GetCreditEnhancement,
  GetAssetSecuritization,
  GetYieldRate,
  ProjectProposalCreate,
  GetAllByAssetTransferId,
  GetHaveAssetTransferedPagedAndSort,
  SecurityCreditRatingGetHaveAssetTransferedProjectName,
  IsExtiseYieldRate
} from "@/api/stu/SupplyChainFinance";
import { nextTick } from "process";
export function usePortrait() {
  const filterDataList = ref()
  const filterSelectId = ref('')
  const filterAssetTransferId = ref()
  const dataList = ref([]);
  const caseList = ref([])
  const caseDialog = ref(false)
  const creditEnhancementVisible = ref(false) //获取当前项目下的信用增级弹窗
  const allDataList = ref([])
  const isShowCaseDetail = ref(false)
  const route = useRoute()
  const DialogVisible = ref<boolean>(false);
  const gradeDetailVisible = ref(false)
  const showCase = ref(false)
  const isExtiseYield = ref(false)
  const EntryPlatform = reactive({
    projectName: '',
    assetTransferId: '',
    assetPoolId: '',
    creditEnhancement: '',
    seniorSubStructureDesign: ''
  })
  // const pagination = reactive({
  //   total: 0,
  //   pageSize: 20,
  //   currentPage: 1,
  //   pageSizes: [10, 20, 50, 100],
  // });
  // const pagination1 = reactive({
  //   total: 0,
  //   pageSize: 20,
  //   currentPage: 1,
  //   pageSizes: [10, 20, 50, 100],
  // });
  const diasbledData = ref([false, false, false, false, false])
  const type = ref()
  const projectList = ref([])
  const caseProjectList = ref([])
  const strongTypeList = ref([])
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "资料类型",
      prop: "creditEnhancementName",
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const allColumns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "项目名称",
      prop: "assetSecuritizationName",
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const columns1: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "方案名称",
      prop: "assetSecuritizationName",
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const designDate = ref([{
    layerName: '',
    priority: '',
    sizePercentage: '',
    totalTerm: '',
  }, {
    layerName: '',
    priority: '',
    sizePercentage: '',
    totalTerm: '',
  }, {
    layerName: '',
    priority: '',
    sizePercentage: '',
    totalTerm: '',
  }, {
    layerName: '',
    priority: '',
    sizePercentage: '',
    totalTerm: '',
  }, {
    layerName: '',
    priority: '',
    sizePercentage: '',
    totalTerm: '',
  }])//type1数据
  //type2数据
  const caseFlowData = reactive({
    basicAssetSize: '', //基础资产池规模
    issuedSecuritiesSize: '',//发行证券规模
    excessCollateralSize: '',//超额抵押资产规模
  })
  //type3数据
  const overcolLateralization = reactive({
    futureCashFlow: '', //未来现金流
    issuanceSize: '',//发行规模
    yieldRate: '',//收益率
    principalAndInterest: '',//证券本息
    cashFlowCoverageRatio: '',//现金流覆盖倍数
  })
  const designSelection = ref([])
  const gradeDetailData = ref() //信用增级详细数据
  const caseData = reactive({
    originalEquityHolder: "", //原始权益人
    planManager: "",//存储计划管理人信息的文本字段
    expectedIssueSize: '',//预计发行规模 
    productTerm: '',//产品期限
    productLimit: '',
    repaymentArrangement: "",//下拉框选择还本付息规则
    expectedIssueRate: '',//预期发行利率
    creditEnhancementMechanism: [],//存储增信机制的文本字段
    creditEnhancementName: '',
    assetTransferId: "",
    assetPoolId: '',
    assetSecuritizationName: '' // 下拉框根据融资放款时选择资产证券化的融资项目显示采购项目名称
  })

  const caseSelectData = ref([])



  onMounted(async () => {
    let data = qs.stringify({
      dictCode: 'CreditEnhancementMethod'
    })
    const res = await GetDictionaryByDictCode(data)
    if (res.success) {
      strongTypeList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    let data1 = qs.stringify({
      dictCode: 'SecondaryStructure'
    })
    const res1 = await GetDictionaryByDictCode(data1)
    if (res1.success) {
      designSelection.value = res1.data
    } else {
      ElMessage.error(res1.msg)
    }
    const data2 = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res2 = await GetHaveAssetTransferedProjectName(data2)
    if (res2.success) {
      projectList.value = res2.data
      caseProjectList.value = res2.data
    } else {
      ElMessage.error(res2.msg)
    }
    //获取列表
    getList1()
    getList2()
  })

  async function getList1() {
    const data = qs.stringify({
      taskId: route.query.taskId,
      planId: route.query.planId
    })
    let res = await GetHaveAssetTransferedPagedAndSort(data)
    if (res.success) {
      allDataList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }
  async function getList2() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await GetAllByAssetTransferId(data)
    if (res.success) {
      caseList.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }
  //新增更换type
  async function changeType(item) {
    if (EntryPlatform.assetTransferId == '') {
      ElMessage.warning('请先选择项目')
      EntryPlatform.creditEnhancement = ''
      return
    }
    if (item.dictName == '优先/次级结构') {
      type.value = 1
    }
    if (item.dictName == '超额抵押') {
      type.value = 2
      const data = qs.stringify({
        asstPoolId: EntryPlatform.assetPoolId
      })
      let res = await GetCreditEnhancementInfoByAssetPoolId(data)
      if (res.success) {
        caseFlowData.issuedSecuritiesSize = res.data.financingAmount
        caseFlowData.excessCollateralSize = Number(caseFlowData.basicAssetSize) - Number(caseFlowData.issuedSecuritiesSize)
      } else {
        ElMessage.error(res.msg)
      }
    }
    if (item.dictName == '超额现金流覆盖') {
      type.value = 3
      const data = qs.stringify({
        asstPoolId: EntryPlatform.assetPoolId
      })
      let res = await GetCreditEnhancementInfoByAssetPoolId(data)
      if (res.success) {
        overcolLateralization.futureCashFlow = Number(res.data.futureCashFlow)
      } else {
        ElMessage.error(res.msg)
      }
      const data1 = qs.stringify({
        assetTransferId: EntryPlatform.assetTransferId
      })
      let res1 = await GetExcessCollateral(data1)
      if (res1.success) {
        overcolLateralization.issuanceSize = Number(res1.data)
      } else {
        EntryPlatform.creditEnhancement = undefined
        type.value = null
        ElMessage.warning('请先完成超额抵押增信方式')
      }
    }
  }
  //信用增级新增
  function addNew() {
    DialogVisible.value = true
  }

  //选择为次级时后续禁用
  function changeDisablde(item) {
    if (item.dictName == '次级') {
      const index = designDate.value.findIndex(item => item.priority == '5a9d92b9569a11eeba2bd08e79d50dfb');
      if (index !== -1) {
        for (let i = index + 1; i < designDate.value.length; i++) {
          designDate.value[i].layerName = '';
          designDate.value[i].priority = '';
          designDate.value[i].sizePercentage = '';
          designDate.value[i].totalTerm = '';
          diasbledData.value[i] = true
        }
      }
    }
  }
  //信用增级切换项目
  async function changeProject(a) {
    EntryPlatform.projectName = a.assetSecuritizationName
    EntryPlatform.assetPoolId = a.assetPoolId
    designDate.value.forEach(item => item.totalTerm = a.termSmallLoan)
    caseFlowData.basicAssetSize = a.smallLoanCreditbalance
  }

  //制定方案切换项目
  async function changeCaseProject(a) {
    caseData.assetSecuritizationName = a.assetSecuritizationName
    caseData.productTerm = a.termSmallLoan
    caseData.assetPoolId = a.assetPoolId
    const data = qs.stringify({
      assetTransferId: caseData.assetTransferId
    })
    let res = await GetExcessCollateral(data)
    if (res.success) {
      caseData.expectedIssueSize = res.data
    } else {
      ElMessage.warning('请先完成超额抵押增信方式')
    }


    let res1 = await IsExtiseYieldRate(data)
    if (res1.data) {
      let expectedIssueRate = await GetYieldRate(data)
      if (expectedIssueRate.success) {
        isExtiseYield.value = true
        caseData.expectedIssueRate = expectedIssueRate.data
      } else {
        ElMessage.warning(expectedIssueRate.msg)
      }
    } else {
      isExtiseYield.value = false
    }


    const data2 = qs.stringify({
      assetTransferId: caseData.assetTransferId,
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res2 = await GetCreditEnhancement(data2)
    if (res2.success) {
      caseSelectData.value = res2.data
      caseData.creditEnhancementName = res2.data.map(item => item.creditEnhancementName).join(',')
      caseData.creditEnhancementMechanism = res2.data.map(item => item.assetSecuritizationId)
    } else {
      ElMessage.error(res2.msg)
    }
  }
  //清空信用增级
  function handleCancel() {
    for (let i = 0; i < designDate.value.length; i++) {
      designDate.value[i].layerName = '';
      designDate.value[i].priority = '';
      designDate.value[i].sizePercentage = '';
      designDate.value[i].totalTerm = '';
      diasbledData.value[i] = false
    }
    type.value = ''
    EntryPlatform.assetTransferId = ''
    EntryPlatform.creditEnhancement = ''
    EntryPlatform.projectName = ''
    caseFlowData.basicAssetSize = ''
    caseFlowData.excessCollateralSize = ''
    caseFlowData.issuedSecuritiesSize = ''
    overcolLateralization.futureCashFlow = ''
    overcolLateralization.cashFlowCoverageRatio = ''
    overcolLateralization.yieldRate = ''
    overcolLateralization.principalAndInterest = ''
    overcolLateralization.issuanceSize = ''
    DialogVisible.value = false
  }
  //提交信用增级 后续可合并下代码
  async function SubtimEntryPlatform() {
    if (EntryPlatform.assetTransferId == '') {
      ElMessage.warning('请选择资产证券化项目')
      return
    }
    if (EntryPlatform.creditEnhancement == '') {
      ElMessage.warning('请选择增信方式')
      return
    }
    if (type.value == '1') {
      let sum = 0
      designDate.value.forEach(item => {
        sum += Number(item.sizePercentage)
      })
      if (sum == 100) {
        const data = {
          projectName: EntryPlatform.projectName,
          creditEnhancement: EntryPlatform.creditEnhancement,
          seniorSubArrangement: JSON.stringify(designDate.value),
          taskId: route.query.taskId,
          planId: route.query.planId,
          assetTransferId: EntryPlatform.assetTransferId,
          type: type.value
        }
        let res = await AssetSecuritizationCreate(data)
        if (res.success) {
          ElMessage.success(res.msg)
          getList1()
          handleCancel()
        } else {
          ElMessage.error(res.msg);
        }
      } else {
        ElMessage.warning('规模占比总和应该是100')
      }
    }
    if (type.value == 2) {
      const data = {
        projectName: EntryPlatform.projectName,
        creditEnhancement: EntryPlatform.creditEnhancement,
        seniorSubArrangement: JSON.stringify(caseFlowData),
        taskId: route.query.taskId,
        planId: route.query.planId,
        assetTransferId: EntryPlatform.assetTransferId,
        type: type.value
      }
      let res = await AssetSecuritizationCreate(data)
      if (res.success) {
        ElMessage.success(res.msg)
        handleCancel()
        getList1()
      } else {
        ElMessage.error(res.msg);
      }
    }

    if (type.value == 3) {
      if (overcolLateralization.yieldRate == '') {
        ElMessage.warning('请先填写收益率！')
        return
      }
      const data = {
        projectName: EntryPlatform.projectName,
        creditEnhancement: EntryPlatform.creditEnhancement,
        seniorSubArrangement: JSON.stringify(overcolLateralization),
        taskId: route.query.taskId,
        planId: route.query.planId,
        assetTransferId: EntryPlatform.assetTransferId,
        type: type.value
      }
      let res = await AssetSecuritizationCreate(data)
      if (res.success) {
        ElMessage.success(res.msg)
        getList1()
        handleCancel()
      } else {
        ElMessage.error(res.msg);
      }
    }
  }

  //type3操作
  function changeIssuanceSize() {
    overcolLateralization.principalAndInterest = (1 + overcolLateralization.yieldRate / 100) * overcolLateralization.issuanceSize
    overcolLateralization.cashFlowCoverageRatio = Number(overcolLateralization.futureCashFlow / overcolLateralization.principalAndInterest).toFixed(2)

    if (overcolLateralization.yieldRate > 5) {
      ElMessage.warning('设置发行利率小于等于5%')
      overcolLateralization.yieldRate = ''
      overcolLateralization.principalAndInterest = ''
      overcolLateralization.cashFlowCoverageRatio = ''
    }
    if (Number(overcolLateralization.cashFlowCoverageRatio) > 1.12) {
      ElMessage.warning('现金流覆盖倍数不超过1.12')
      overcolLateralization.yieldRate = ''
      overcolLateralization.principalAndInterest = ''
      overcolLateralization.cashFlowCoverageRatio = ''
    }
  }
  function changeExpectedIssueRate() {
    if (Number(caseData.expectedIssueRate) > 5) {
      ElMessage.warning('预期发行利率不大于5%')
      caseData.expectedIssueRate = 0
    }
    if (Number(caseData.expectedIssueRate) < 0) {
      ElMessage.warning('预期发行利率不小于0')
      caseData.expectedIssueRate = 0
    }
  }

  //查看增级详情
  async function showGradeDetail(item) {
    const data = qs.stringify({
      assetSecuritizationId: item.assetSecuritizationId
    })
    let res = await GetAssetSecuritization(data)
    if (res.success) {
      res.data.seniorSubArrangement = JSON.parse(res.data.seniorSubArrangement)
      gradeDetailData.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
    gradeDetailVisible.value = true
  }

  //查看该项目下的信用增级
  function filterProject(a) {
    filterAssetTransferId.value = a.assetTransferId
    getDataList()
  }
  async function getDataList() {
    const data = qs.stringify({
      assetTransferId: filterAssetTransferId.value,
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res = await GetCreditEnhancement(data)
    if (res.success) {
      dataList.value = res.data
      creditEnhancementVisible.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }

  function closeCaseDialog() {
    caseData.assetPoolId = ''
    caseData.assetSecuritizationName = ''
    caseData.assetTransferId = ''
    caseData.creditEnhancementMechanism = []
    caseData.expectedIssueRate = ''
    caseData.expectedIssueSize = ''
    caseData.originalEquityHolder = ''
    caseData.planManager = ''
    caseData.productLimit = ''
    caseData.productTerm = ''
    caseData.repaymentArrangement = ''
    caseDialog.value = false
    isShowCaseDetail.value = false

  }

  async function saveCase() {
    if (caseData.assetTransferId == '') {
      ElMessage.warning('请选择资产证券化项目');
      return
    }
    const data = {
      originalEquityHolder: '****',
      planManager: "****",
      expectedIssueSize: caseData.expectedIssueSize,
      productTerm: caseData.productTerm,
      repaymentArrangement: caseData.repaymentArrangement,
      expectedIssueRate: Number(caseData.expectedIssueRate),
      creditEnhancementMechanism: caseData.creditEnhancementMechanism.join(';'),
      assetTransferId: caseData.assetTransferId,
      assetSecuritizationName: caseData.assetSecuritizationName,
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await ProjectProposalCreate(data)
    if (res.success) {
      ElMessage.success(res.msg)
      closeCaseDialog()
      getList2()
    } else {
      ElMessage.error(res.msg);
    }
  }

  async function showCaseDetail(item) {
    const data2 = qs.stringify({
      assetTransferId: item.assetTransferId,
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res2 = await GetCreditEnhancement(data2)
    if (res2.success) {
      caseSelectData.value = res2.data
    } else {
      ElMessage.error(res2.msg)
    }
    caseData.assetTransferId = item.assetTransferId
    caseData.expectedIssueSize = item.expectedIssueSize
    caseData.productTerm = item.productTerm
    caseData.repaymentArrangement = item.repaymentArrangement
    caseData.expectedIssueRate = item.expectedIssueRate
    caseData.creditEnhancementMechanism = item.creditEnhancementMechanism.split(';')
    caseData.creditEnhancementName = res2.data.map(item => item.creditEnhancementName).join(',')
    isShowCaseDetail.value = true
    caseDialog.value = true
  }
  return {
    dataList,
    allDataList,
    EntryPlatform,
    DialogVisible,
    addNew,
    designDate,
    strongTypeList,
    designSelection,
    projectList,
    type,
    changeType,
    overcolLateralization,
    caseFlowData,
    diasbledData,
    changeDisablde,
    handleCancel,
    changeProject,
    SubtimEntryPlatform,
    filterDataList,
    filterProject,
    showGradeDetail,
    gradeDetailVisible,
    changeIssuanceSize,
    showCase,
    caseList,
    filterSelectId,
    caseDialog,
    closeCaseDialog,
    saveCase,
    gradeDetailData,
    caseData,
    caseProjectList,
    changeCaseProject,
    caseSelectData,
    // changeProductTerm,
    showCaseDetail,
    isShowCaseDetail,
    columns,
    allColumns,
    columns1,
    creditEnhancementVisible,
    isExtiseYield,
    changeExpectedIssueRate
  }
}